package makabakaquestionnaire.zutsoftware.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.Data;
import makabakaquestionnaire.zutsoftware.constant.Result;
import makabakaquestionnaire.zutsoftware.entity.*;
import makabakaquestionnaire.zutsoftware.entity.request.QueryProjectRequest;
import makabakaquestionnaire.zutsoftware.entity.vo.ProjectPreviewVo;
import makabakaquestionnaire.zutsoftware.enums.ProjectStatusEnum;
import makabakaquestionnaire.zutsoftware.framework.security.Service.TokenService;
import makabakaquestionnaire.zutsoftware.framework.security.model.LoginUser;
import makabakaquestionnaire.zutsoftware.service.IProjectTemplateItemService;
import makabakaquestionnaire.zutsoftware.service.IProjectTemplateService;
import makabakaquestionnaire.zutsoftware.service.impl.ProjectItemServiceImpl;
import makabakaquestionnaire.zutsoftware.service.impl.ProjectThemeServiceImpl;
import makabakaquestionnaire.zutsoftware.service.impl.UserProjectServiceImpl;
import makabakaquestionnaire.zutsoftware.system.entity.CourseProject;
import makabakaquestionnaire.zutsoftware.system.service.ICourseProjectService;
import makabakaquestionnaire.zutsoftware.utils.ServletUtils;
import makabakaquestionnaire.zutsoftware.utils.String.StringUtils;
import makabakaquestionnaire.zutsoftware.utils.UUidUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Date;
import java.util.List;

@Api(tags = "问卷的接口")
@RestController
@RequestMapping("project")
public class UserProjectController {
    ProjectThemeServiceImpl projectThemeService;
    UserProjectServiceImpl userProjectService;
    ProjectItemServiceImpl projectItemService;
    @Autowired
    private ICourseProjectService courseProjectService;
    @Autowired
    private IProjectTemplateService templateService;
    @Autowired
    private IProjectTemplateItemService templateItemService;

    @Autowired
    public void setUserProjectService(UserProjectServiceImpl userProjectService) {
        this.userProjectService = userProjectService;
    }

    @Autowired
    public void setProjectThemeService(ProjectThemeServiceImpl projectThemeService) {
        this.projectThemeService = projectThemeService;
    }

    @Autowired
    public void setProjectItemService(ProjectItemServiceImpl projectItemService) {
        this.projectItemService = projectItemService;
    }
    @Autowired
    private TokenService tokenService;

    @ApiOperation("测试用：查询所有问卷，包括不同用户的")
    @GetMapping("/list")
    public Result queryAll() {
        return Result.success(userProjectService.queryAll());
    }

    @ApiOperation("测试用：根据用户的id查询所有问卷")
    @GetMapping("/user/{id}")
    public Result SelectByUserId(@PathVariable Long id) {
        return Result.success(userProjectService.queryProjectByUserID(id));
    }

    /**
     * 根据问卷状态+正在登陆的用户名查询问卷
     *
     * @param req
     * @param status
     * @return
     */

    @ApiOperation("测试用：根据问卷状态+正在登陆的用户名查询问卷")
    @GetMapping("/status/{status}")
    public Result queryProjectWithStatus(HttpServletRequest req, @PathVariable Long status) {
        Principal principal = req.getUserPrincipal();
        String username = principal.getName();
        return Result.success(userProjectService.queryProjectWithStatus(status, username));
    }


    @ApiOperation("根据queryProjectRequest查询所有问卷，条件查询包括：模糊名称，是否删除，日期，项目状态,可动态添加,用户id不用填写，后端登陆有保存")
    @PostMapping("/page")
    public Result queryProjectByName(@RequestBody QueryProjectRequest queryProjectRequest) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        queryProjectRequest.setUserId(loginUser.getUser().getId());
        if (StringUtils.isNotEmpty(queryProjectRequest.getCourseId())){
            queryProjectRequest.setUserId(null);
        }
        return Result.success(userProjectService.queryProjectByRequest(queryProjectRequest));
    }

    @GetMapping("/page/{status}/{username}")
    public Result queryProjectGet(@PathVariable Long status, @PathVariable String username) {
        return Result.success(userProjectService.queryProjectByRequest(status, username));
    }

    /**
     * 创建问卷，前端传project对象只需包括project_describe,和project_name属性
     *
     * @param
     */
    @ApiOperation("创建问卷，前端传project对象只需包括project_describe,和project_name属性，其他在后端加工")
    @PostMapping("/create")
//    public Result insertProject(@ApiParam(defaultValue = "只用包含project_describe,和project_name属性") @RequestBody UserProject project,@RequestBody String courseId) {
    public Result insertProject(@ApiParam(defaultValue = "只用包含project_describe,和project_name属性") @RequestBody ProjectCourse pc) {
        //@AuthenticationPrincipal LoginUser users
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        UserProject project= pc.getProject();
        String courseId=pc.getCourseId();
        project.setProjectKey(UUidUtil.getSimpleUUID());
        project.setStatus(ProjectStatusEnum.CREATE.getValue());
        project.setUserId((loginUser.getUser().getId()));
        project.setUserName(loginUser.getUsername());
        //当前时间字符串，格式：yyyy-MM-dd HH:mm:ss
        String now = DateUtil.now();
        Date date = DateUtil.parse(now);   //转为date格式
        project.setCreateTime(date);
        project.setUpdateTime(date);
        userProjectService.insertProject(project);
        if (StringUtils.isNotEmpty(courseId)){
            CourseProject courseProject=new CourseProject(Long.parseLong(courseId),project.getProjectKey());
            courseProjectService.insertCourseProject(courseProject);
        }
        return Result.success(project.getProjectKey());
    }

    /**
     * 使用模板，将模板写入到问卷库并关联
     * @param projectKey
     * @param courseId
     * @return
     */
    @GetMapping("/userTemplate/{projectKey}/{courseId}")
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Result userTemplate(@PathVariable String projectKey,@PathVariable String courseId){
        ProjectTemplate projectTemplate = templateService.selectProjectTemplateByKey(projectKey);
        UserProject userProject=new UserProject();
        BeanUtils.copyProperties(projectTemplate,userProject,"updateTime","id");
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        userProject.setStatus(projectTemplate.getStatus());
        userProject.setUserId((loginUser.getUser().getId()));
        userProject.setUserName(loginUser.getUsername());
        userProject.setProjectKey(UUidUtil.getSimpleUUID());
        userProjectService.insertProject(userProject);
        if (StringUtils.isNotEmpty(courseId)){
            CourseProject courseProject=new CourseProject(Long.parseLong(courseId),userProject.getProjectKey());
            courseProjectService.insertCourseProject(courseProject);
        }
        ProjectTemplateItem projectTemplateItem=new ProjectTemplateItem();
        projectTemplateItem.setProjectKey(projectKey);
        List<ProjectTemplateItem> projectTemplateItems = templateItemService.selectProjectTemplateItemList(projectTemplateItem);
        for (ProjectTemplateItem templateItem : projectTemplateItems) {
            ProjectItem projectItem=new ProjectItem();
            BeanUtils.copyProperties(templateItem,projectItem,"updateTime","id");
            projectItem.setSort(templateItem.getItemSort());
            projectItem.setExtend(templateItem.getExtend());
            projectItem.setDefaultValue(templateItem.getDefaultvalue());
            projectItem.setProjectKey(userProject.getProjectKey());
            projectItem.setSpan(templateItem.getItemSpan().intValue());
            projectItemService.insertProjectItem(projectItem);
        }
        return Result.success(userProject.getProjectKey(),"操作成功");
    }

    /**
     * 更新问卷，前端传project对象只需包括project_describe,和project_name属性和id
     *
     * @param project
     */
    @ApiOperation("更新问卷，前端传project对象只需包括project_describe,和project_name属性和id，其他在后端加工")
    @PostMapping("/update")
    public Result updateProject(@RequestBody UserProject project) {
        UserProject oldProject = userProjectService.queryProjectByProKey(project.getProjectKey());
        String now = DateUtil.now();
        Date date = DateUtil.parse(now);
        project.setUpdateTime(date);
        boolean update = false;
        if (ObjectUtil.isNotEmpty(oldProject)) {
            update = userProjectService.updateProject(project);
        }
        return Result.success(project, "问卷更新" + update);
    }

    @ApiOperation("停止问卷收集")
    @PostMapping("/stop")
    public Result stopProject(@RequestBody UserProject project) {
        UserProject oldProject = userProjectService.queryProjectByProKey(project.getProjectKey());
        boolean update = false;
        if (ObjectUtil.isNotEmpty(oldProject)) {
            oldProject.setStatus(3);
            update = userProjectService.updateProject(oldProject);
        }
        return Result.success(oldProject, "问卷停止收集" + update);
    }

    @ApiOperation("问卷发布")
    @PostMapping("/publish")
    public Result publishProject(@RequestBody UserProject project) {
        List<ProjectItem> count = projectItemService.queryProjectItemByProKey(project.getProjectKey());
        if (count.size() == 0) {
            return Result.failed("无有效表单项(item)，无法发布");
        }
        UserProject oldProject = userProjectService.queryProjectByProKey(project.getProjectKey());
        boolean update = false;
        if (ObjectUtil.isNotEmpty(oldProject)) {
            oldProject.setStatus(2);
            update = userProjectService.updateProject(oldProject);
        }
        return Result.success(oldProject, "问卷发布" + update);
    }

    /**
     * 删除问卷，实际上更新问卷的is_delete字段
     * 参数包含project_key即可
     *
     * @param project
     */
    @ApiOperation("删除问卷，实际上更新问卷的is_delete字段，参数包含project_key即可")
    @PostMapping("/delete")
    public Result deleteProject(@RequestBody UserProject project) {
        UserProject oldProject = userProjectService.queryProjectByProKey(project.getProjectKey());
        oldProject.setDelete(true);
        userProjectService.updateProject(oldProject);
        return Result.success(oldProject.getProjectKey(), "删除成功");
    }

    @ApiOperation("恢复问卷，从回收站恢复，实际上更新问卷的is_delete字段，参数包含project_key即可")
    @PostMapping("/restore")
    public Result restoreProject(@RequestBody UserProject project) {
        project.setDelete(false);
        boolean update = userProjectService.updateProject(project);
        return Result.success(project.getProjectKey(), "恢复" + update);
    }

    @ApiOperation("预览问卷所需的数据（project,projectItem,projectTheme）")
    @GetMapping("/preview/{proKey}")
    public Result previewProject(@PathVariable String proKey) {
        UserProject userProject = userProjectService.queryProjectByProKey(proKey);
        List<ProjectItem> projectItems = projectItemService.queryProjectItemByProKey(proKey);
        ProjectTheme projectTheme = projectThemeService.queryProjectThemeByProKey(proKey);
        ProjectPreviewVo projectPreviewVo = new ProjectPreviewVo(userProject, projectItems, projectTheme);
        return Result.success(projectPreviewVo, "问卷预览数据");
    }

    @GetMapping("/getStatus/{proKey}")
    public Result getStatus(@PathVariable String proKey) {
        UserProject project = userProjectService.queryProjectByProKey(proKey);
        return Result.success(project.getStatus());
    }

    @PostMapping("/theme/save")
    public Result saveOrUpdateTheme(@RequestBody ProjectTheme projectTheme) {
        ProjectTheme oldTheme = projectThemeService.queryProjectThemeByProKey(projectTheme.getProjectKey());
        if (ObjectUtil.isNotEmpty(oldTheme)) {
            boolean update = projectThemeService.updateProjectTheme(projectTheme);
            return Result.success(projectTheme, "主题更新" + update);
        } else {
            boolean create = projectThemeService.saveProjectTheme(projectTheme);
            return Result.success(projectTheme, "主题创建" + create);
        }
    }

    @PostMapping("/theme/getByKey")
    public Result getThemeByKey(@RequestBody ProjectTheme projectTheme) {
        ProjectTheme theme = projectThemeService.queryProjectThemeByProKey(projectTheme.getProjectKey());
        return Result.success(theme);
    }

}
@Data
class ProjectCourse {
    private UserProject project;
    private String courseId;
}
